<?php
declare (strict_types=1);

namespace app\sysuser\controller\system;

use app\common\controller\SysBackend;
use app\common\enums\AcceptAccountTypeEnum;
use app\common\enums\NotificationStatusEnum;
use app\common\model\banxi\sys\SysNotification as SysNotificationModel;
use app\common\model\banxi\sys\SysNotificationAccept;
use ba\Exception;
use think\db\exception\DbException;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Validate;
use think\validate\ValidateRule;

class SysNotification extends SysBackend
{
    protected array $noNeedLogin = [];
    protected array $noNeedPermission = [];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new SysNotificationModel();
    }


    /**
     * 分页查询
     * @return void
     * @throws DbException
     */
    public function listPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query"]);
        //查询条件解析
        $where = get_query($param);
        //获取分页数据
        $pageParams = get_page_params($param);
        $list = $this->model->getListPage($where, $pageParams['page'], $pageParams['limit']);
        $this->ok('操作成功', result_row($list));
    }

    /**
     * 查询
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get()
    {
        $param = $this->request->param(["query" => []]);
        if (empty($param['query'])) {
            $this->fail('请传递你要查询的记录');
        }
        $where = get_query($param);
        $info = $this->model->getInfo($where);
        if (empty($info)) {
            $this->fail('记录不存在');
        }
        $this->ok('操作成功', $info);
    }

    /**
     * 新增或修改
     * @return void
     */
    public function save()
    {
        $param = $this->request->param();
        Db::startTrans();
        try {
            $accountIds = $param['accountIds'];
            $accountType = $param['accountType'];
            $model = $param;
            if ($accountType == AcceptAccountTypeEnum::ALL) {
                $model['isAll'] = 1;
            } else {
                if (empty($accountIds)) {
                    throw new ValidateException('请选择接收人');
                }
                $model['isAll'] = 0;
            }
            $model['status'] = NotificationStatusEnum::E1;
            $this->model->save($model);
            $notificationId = $this->model->id;
            if (!$model['isAll']) {
                $notificationAccepts = [];
                foreach ($accountIds as $accountId) {
                    $notificationAccept = [
                        'notificationId' => $notificationId,
                        'accountId' => $accountId,
                        'accountType' => $accountType,
                    ];
                    $sysNotificationAcceptModel = new SysNotificationAccept();
                    $notificationAccept = array_merge($notificationAccept, $sysNotificationAcceptModel->accountFill($accountType, $accountId));
                    $notificationAccepts[] = $notificationAccept;
                }
                $sysNotificationAccept = new SysNotificationAccept();
                $sysNotificationAccept->saveAll($notificationAccepts);
            }
            Db::commit();
        } catch (ValidateException|Exception|PDOException $e) {
            Db::rollback();
            $this->fail($e->getMessage());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }


    public function del()
    {
        $param = $this->request->param(['ids' => []]);
        try {
            $validate = Validate::rule([
                'ids' => ValidateRule::isRequire(null, '请选择你要删除的记录'),
            ]);
            if (!$validate->check($param)) throw new ValidateException($validate->getError());
            SysNotificationModel::destroy(function ($query) use ($param) {
                $query->whereIn('id', $param['ids']);
            });
        } catch (ValidateException $exception) {
            $this->fail($exception->getMessage());
        }
        $this->ok('操作成功', [], self::NOTIFICATION);
    }
}
